package com.yonyou.jrmob.contacts.contact.view.dialog;


import android.app.Activity;
import android.app.AlertDialog;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.NumberPicker.Formatter;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.TextView;

import com.yonyou.jrmob.contacts.R;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * Created by Administrator on 2016/7/17.
 */
public class DateTimeSetDialogUtil implements Formatter,OnDateChangedListener,OnValueChangeListener{
    private DatePicker datePicker;
    private NumberPicker hourPicker;
    private NumberPicker minutePicker;
    private AlertDialog ad;
    private String dateTime;
    private String initDateTime;
    private Activity activity;
    private TextView show_date;
    private Button cancel_btn;
    private Button select_btn;
    private boolean isDate ;//是否显示时间选择器
    private TextView hour_text;
    private TextView min_text;

    /**
     * 日期时间弹出选择框构造函数
     *
     * @param activity
     *            ：调用的父activity
     * @param initDateTime
     *            初始日期时间值，作为弹出窗口的标题和日期时间初始值
     */
    public DateTimeSetDialogUtil(Activity activity, String initDateTime, boolean isDate) {
        this.activity = activity;
        this.initDateTime = initDateTime;
        this.isDate = isDate;
    }

    public String format(int value) {
        String tmpStr = String.valueOf(value);
        if (value < 10) {
            tmpStr = "0" + tmpStr;
        }
        return tmpStr;
    }

    public void init(DatePicker datePicker, NumberPicker hourPicker,NumberPicker MinutePicker) {
        Calendar calendar = Calendar.getInstance();
        if (!(null == initDateTime || "".equals(initDateTime))) {
            calendar = this.getCalendarByInintData(initDateTime);
        } else {

            initDateTime = calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.MONTH) + "月"
                    + calendar.get(Calendar.DAY_OF_MONTH) + "日 "
                    + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
        }

        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), this);
        hourPicker.setOnValueChangedListener(this);
        hourPicker.setFormatter(this);
        hourPicker.setMaxValue(24);
        hourPicker.setMinValue(0);
        hourPicker.setValue(calendar.get(Calendar.HOUR_OF_DAY));

        String[] minute = {"00","30"};
        minutePicker.setOnValueChangedListener(this);
        minutePicker.setDisplayedValues(minute);
        minutePicker.setMinValue(0);
        minutePicker.setMaxValue(minute.length - 1);
        /*if (calendar.get(Calendar.MINUTE)<30){
            minutePicker.setValue(00);
        }else{
            minutePicker.setValue(30);
        }*/
    }
    public void init(DatePicker datePicker) {
        Calendar calendar = Calendar.getInstance();
        if (!(null == initDateTime || "".equals(initDateTime))) {
            calendar = this.getCalendarByInintData(initDateTime);
        } else {

            initDateTime = calendar.get(Calendar.YEAR) + "年" + calendar.get(Calendar.MONTH) + "月"
                    + calendar.get(Calendar.DAY_OF_MONTH) + "日 "
                    + calendar.get(Calendar.HOUR_OF_DAY) + ":" + calendar.get(Calendar.MINUTE);
        }

        datePicker.init(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), this);
    }

    /**
     * 弹出日期时间选择框方法
     *
     * @param inputDate
     *            :为需要设置的日期时间文本编辑框
     * @return
     */
    public AlertDialog dateTimePicKDialog(final EditText inputDate) {

        ad = new AlertDialog.Builder(activity).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.common_datetime_ct);

        cancel_btn = (Button) window.findViewById(R.id.cancel_btn);
        select_btn = (Button) window.findViewById(R.id.select_btn);
        show_date = (TextView) window.findViewById(R.id.show_date);
        datePicker = (DatePicker) window.findViewById(R.id.datepicker);
        hourPicker = (NumberPicker) window.findViewById(R.id.hourpicker);
        minutePicker = (NumberPicker) window.findViewById(R.id.minutepicker);
        hour_text = (TextView) window.findViewById(R.id.hour_text);
        min_text = (TextView) window.findViewById(R.id.min_text);
        if (isDate){
            hour_text.setVisibility(View.GONE);
            min_text.setVisibility(View.GONE);
            hourPicker.setVisibility(View.GONE);
            minutePicker.setVisibility(View.GONE);
            init(datePicker);
        }else{
            init(datePicker, hourPicker,minutePicker);
        }

        show_date.setText(initDateTime);
        cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputDate.setText("");
                ad.dismiss();
            }
        });
        select_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputDate.setText(dateTime);
                ad.dismiss();
            }
        });
        //ad.getWindow().setLayout(800,1300);
        onDateChanged(null, 0, 0, 0);
        return ad;
    }

    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        // 获得日历实例
        Calendar calendar = Calendar.getInstance();
        calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        dateTime = sdf1.format(calendar.getTime());

        if (isDate){
        }else{
            String date_day = String.format("%02d",hourPicker.getValue());
            dateTime += " "+date_day + ":" + minutePicker.getDisplayedValues()[minutePicker.getValue()];
        }
        show_date.setText(dateTime);
    }
    @Override
    public void onValueChange(NumberPicker numberPicker, int i, int i1) {
        onDateChanged(null, 0, 0, 0);
    }

    /**
     * 实现将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒,并赋值给calendar
     *
     * @param initDateTime
     *            初始日期时间值 字符串型
     * @return Calendar
     */
    private Calendar getCalendarByInintData(String initDateTime) {
        Calendar calendar = Calendar.getInstance();

        // 将初始日期时间2012年07月02日 16:45 拆分成年 月 日 时 分 秒
        String date = spliteString(initDateTime, "日", "index", "front"); // 日期
        String time = spliteString(initDateTime, "日", "index", "back"); // 时间

        String yearStr = spliteString(date, "年", "index", "front"); // 年份
        String monthAndDay = spliteString(date, "年", "index", "back"); // 月日

        String monthStr = spliteString(monthAndDay, "月", "index", "front"); // 月
        String dayStr = spliteString(monthAndDay, "月", "index", "back"); // 日

        String hourStr = spliteString(time, ":", "index", "front"); // 时
        String minuteStr = spliteString(time, ":", "index", "back"); // 分

        int currentYear = Integer.valueOf(yearStr.trim()).intValue();
        int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
        int currentDay = Integer.valueOf(dayStr.trim()).intValue();
        int currentHour = Integer.valueOf(hourStr.trim()).intValue();
        int currentMinute = Integer.valueOf(minuteStr.trim()).intValue();

        calendar.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
        return calendar;
    }
    /**
     * 截取子串
     *
     * @param srcStr
     *            源串
     * @param pattern
     *            匹配模式
     * @param indexOrLast
     * @param frontOrBack
     * @return
     */
    public static String spliteString(String srcStr, String pattern, String indexOrLast,
                                      String frontOrBack) {
        String result = "";
        int loc = -1;
        if (indexOrLast.equalsIgnoreCase("index")) {
            loc = srcStr.indexOf(pattern); // 取得字符串第一次出现的位置
        } else {
            loc = srcStr.lastIndexOf(pattern); // 最后一个匹配串的位置
        }
        if (frontOrBack.equalsIgnoreCase("front")) {
            if (loc != -1)
                result = srcStr.substring(0, loc); // 截取子串
        } else {
            if (loc != -1)
                result = srcStr.substring(loc + 1, srcStr.length()); // 截取子串
        }
        return result;
    }


}
